package com.flower.controller.admin;

import com.flower.annotation.Log;
import com.flower.service.EncyclopediaExcelService;
import com.flower.utils.AjaxResult;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import static com.flower.utils.AjaxResult.error;
import static com.flower.utils.AjaxResult.success;

/**
 * 管理端花卉百科Excel导入导出
 */
@Slf4j
@RestController
@RequestMapping("/admin/encyclopedia/excel")
public class EncyclopediaExcelController{

    @Autowired
    private EncyclopediaExcelService excelService;

    /**
     * 下载花卉百科导入模板
     */
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("花卉百科导入模板.xlsx", StandardCharsets.UTF_8.toString());
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            
            // 生成Excel文件
            excelService.downloadTemplate(response.getOutputStream());
            
            // 刷新输出流
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("下载模板失败", e);
            throw new RuntimeException("下载模板失败");
        }
    }

    /**
     * 导入花卉百科数据
     */
    @Log(name = "导入花卉百科数据")
    @PostMapping("/import")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) {
        try {
            int count = excelService.importEncyclopediaData(file);
            return success("成功导入" + count + "条数据", count);
        } catch (Exception e) {
            log.error("导入数据失败", e);
            return error("导入数据失败：" + e.getMessage());
        }
    }
}